// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.doris.nereids.trees.expressions.functions.scalar;

import org.apache.doris.catalog.FunctionSignature;
import org.apache.doris.nereids.exceptions.AnalysisException;
import org.apache.doris.nereids.trees.expressions.Expression;
import org.apache.doris.nereids.trees.expressions.functions.CustomSignature;
import org.apache.doris.nereids.trees.expressions.functions.Monotonic;
import org.apache.doris.nereids.trees.expressions.functions.PropagateNullLiteral;
import org.apache.doris.nereids.trees.expressions.functions.PropagateNullable;
import org.apache.doris.nereids.trees.expressions.literal.StringLikeLiteral;
import org.apache.doris.nereids.trees.expressions.shape.BinaryExpression;
import org.apache.doris.nereids.trees.expressions.visitor.ExpressionVisitor;
import org.apache.doris.nereids.types.DataType;
import org.apache.doris.nereids.types.DateTimeV2Type;
import org.apache.doris.nereids.types.VarcharType;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;

import java.util.List;

/**
 * ScalarFunction 'date_trunc'. This class is generated by GenerateFunction.
 */
public class DateTrunc extends ScalarFunction
        implements BinaryExpression, PropagateNullLiteral, PropagateNullable, Monotonic, CustomSignature {
    private static final List<String> LEGAL_TIME_UNIT =
            ImmutableList.of("year", "quarter", "month", "week", "day", "hour", "minute", "second");

    /**
     * constructor with 2 arguments.
     */
    public DateTrunc(Expression arg0, Expression arg1) {
        super("date_trunc", arg0, arg1);
    }

    /** constructor for withChildren and reuse signature */
    private DateTrunc(ScalarFunctionParams functionParams) {
        super(functionParams);
    }

    @Override
    public void checkLegalityBeforeTypeCoercion() {
        boolean firstArgIsStringLiteral =
                getArgument(0).isConstant() && getArgument(0) instanceof StringLikeLiteral;
        boolean secondArgIsStringLiteral =
                getArgument(1).isConstant() && getArgument(1) instanceof StringLikeLiteral;
        if (!firstArgIsStringLiteral && !secondArgIsStringLiteral) {
            throw new AnalysisException("the time unit parameter of "
                    + getName() + " function must be a string constant: " + toSql());
        } else if (firstArgIsStringLiteral && secondArgIsStringLiteral) {
            if (!LEGAL_TIME_UNIT.contains(((StringLikeLiteral) getArgument(0)).getStringValue().toLowerCase())
                    && !LEGAL_TIME_UNIT.contains(((StringLikeLiteral) getArgument(1))
                    .getStringValue().toLowerCase())) {
                throw new AnalysisException("date_trunc function time unit param only support argument is "
                        + String.join("|", LEGAL_TIME_UNIT));
            }
        } else {
            final String constParam = ((StringLikeLiteral) getArgument(firstArgIsStringLiteral ? 0 : 1))
                    .getStringValue().toLowerCase();
            if (!LEGAL_TIME_UNIT.contains(constParam)) {
                throw new AnalysisException("date_trunc function time unit param only support argument is "
                        + String.join("|", LEGAL_TIME_UNIT));
            }
        }
    }

    /**
     * withChildren.
     */
    @Override
    public DateTrunc withChildren(List<Expression> children) {
        Preconditions.checkArgument(children.size() == 2);
        return new DateTrunc(getFunctionParams(children));
    }

    @Override
    public FunctionSignature customSignature() {
        // should never return V1 Type
        if (getArgument(0).getDataType().isDateLikeType()) {
            DataType type = DataType.getCurrentType(getArgument(0).getDataType());
            return FunctionSignature.ret(type).args(type, VarcharType.SYSTEM_DEFAULT);
        } else if (getArgument(1).getDataType().isDateLikeType()) {
            DataType type = DataType.getCurrentType(getArgument(1).getDataType());
            return FunctionSignature.ret(type).args(VarcharType.SYSTEM_DEFAULT, type);
        }

        boolean firstArgIsStringLiteral =
                getArgument(0).isConstant() && getArgument(0) instanceof StringLikeLiteral;
        boolean secondArgIsStringLiteral =
                getArgument(1).isConstant() && getArgument(1) instanceof StringLikeLiteral;
        if (firstArgIsStringLiteral && !secondArgIsStringLiteral) {
            return FunctionSignature.ret(DateTimeV2Type.WILDCARD)
                    .args(VarcharType.SYSTEM_DEFAULT, DateTimeV2Type.WILDCARD);
        } else if (!firstArgIsStringLiteral && secondArgIsStringLiteral) {
            return FunctionSignature.ret(DateTimeV2Type.WILDCARD)
                    .args(DateTimeV2Type.WILDCARD, VarcharType.SYSTEM_DEFAULT);
        } else if (firstArgIsStringLiteral && secondArgIsStringLiteral) {
            boolean timeUnitIsFirst = LEGAL_TIME_UNIT.contains(((StringLikeLiteral) getArgument(0))
                    .getStringValue().toLowerCase());
            return timeUnitIsFirst ? FunctionSignature.ret(DateTimeV2Type.WILDCARD)
                    .args(VarcharType.SYSTEM_DEFAULT, DateTimeV2Type.WILDCARD)
                    : FunctionSignature.ret(DateTimeV2Type.WILDCARD)
                            .args(DateTimeV2Type.WILDCARD, VarcharType.SYSTEM_DEFAULT);
        }
        // if both of args are not constant, `checkLegalityBeforeTypeCoercion` will throw exception so just return
        // a signature here.
        return FunctionSignature.ret(DateTimeV2Type.WILDCARD)
                .args(VarcharType.SYSTEM_DEFAULT, DateTimeV2Type.WILDCARD);
    }

    @Override
    public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
        return visitor.visitDateTrunc(this, context);
    }

    @Override
    public boolean isPositive() {
        return true;
    }

    @Override
    public int getMonotonicFunctionChildIndex() {
        return getArgument(0).getDataType().isDateLikeType() ? 0 : 1;
    }

    @Override
    public Expression withConstantArgs(Expression literal) {
        return getArgument(0).getDataType().isDateLikeType()
                ? new DateTrunc(literal, child(1)) : new DateTrunc(child(0), literal);
    }
}
